package com.xinchen.all.ui.activity

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContract
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.maple.base.base.BaseActivity
import com.maple.ble.classic.CoroutineClient
import com.maple.ble.classic.ReadData
import com.maple.ble.classic.client.ClientType
import com.maple.ble.classic.client.ConnectState
import com.maple.ble.classic.client.Device
import com.maple.common.utils.Tools
import com.maple.utils.util.LogUtils
import com.xinchen.all.R
import com.xinchen.all.ui.adapter.BluetoothClassicDeviceAdapter
import kotlinx.coroutines.launch
import java.util.UUID

class BluetoothClassicActivity : BaseActivity() {

    private var btnBluetooth: Button? = null
    private var btnDisconnect: Button? = null
    private var rvList: RecyclerView? = null
    private var tvResult: TextView? = null

    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothLeScanner : BluetoothLeScanner? = null

    private val listAdapter: BluetoothClassicDeviceAdapter by lazy {
        BluetoothClassicDeviceAdapter(this).apply {
            this.setData(arrayListOf())
            this.setListener(object : BluetoothClassicDeviceAdapter.OnClickListener{
                override fun onItemClick(pos: Int, device: Device?) {
                    device?.let {
                        lifecycleScope.launch {
                            runOnUiThread {
                                showLoading()
                            }
                            bluetoothClient?.connect(device, 85, 15000, 3)?.collect{ connectState ->
                                runOnUiThread {
                                    dismissLoading()
                                    LogUtils.logGGQ("连接状态：${connectState.name}")
                                    tvResult?.text = "连接状态：${connectState.name}"
                                }
                                if(connectState == ConnectState.CONNECTED){
                                    receiveData(device)
                                }
                            }
                        }
                    }
                }
            })
        }
    }


    private val GET_DEVICE_NUM: String = "05000002080F0F"
    private val GET_WEIGHT_MQTT: String = "05000002010806"
    private fun receiveData(device: Device) {
        lifecycleScope.launch {
            val sendDeviceNumResult = bluetoothClient?.sendData(uuid, Tools.hexStr2Bytes(GET_DEVICE_NUM))?: false
            if(sendDeviceNumResult){
                runOnUiThread {
                    LogUtils.logGGQ("发送NUM数据成功")
                }
            }

            bluetoothClient?.receiveData(uuid)?.collect{ data ->
                val hexData = Tools.bytesToHexString(data.data,data.length)
                val isDealMqtt = Tools.isDealMqtt(hexData)
                LogUtils.logGGQ("isDealMqtt：${isDealMqtt}")

                if (isDealMqtt) {
                    val sendWeightMqttResult = bluetoothClient?.sendData(uuid, Tools.hexStr2Bytes(GET_WEIGHT_MQTT))?: false
                    if(sendWeightMqttResult){
                        runOnUiThread {
                            LogUtils.logGGQ("发送WEIGHT数据成功")
                        }
                    }

                    runOnUiThread {
                        dealMqtt(data)
                    }
                } else {
                    runOnUiThread {
                        dealWeightOld(data)
                    }
                }
            }
        }
    }


    private fun dealMqtt(data: ReadData) {
        val readMessage = " " + Tools.bytesToHexString(data.data, data.length)
        val deviceNum = Tools.getDealMqttDeviceNum(readMessage)
        if(!TextUtils.isEmpty(deviceNum)) {
            LogUtils.logGGQ("设备号：${deviceNum}")
        }

       val weight = Tools.dealMqtt(readMessage)
        if(!TextUtils.isEmpty(weight)) {
            LogUtils.logGGQ("白色表头重量：${weight}")
            tvResult?.text = "${"白色表头重量：${weight}"}"
        } else {
            LogUtils.logGGQ("白色表头重量获取失败")
        }

    }

    private fun dealWeightOld(data: ReadData) {
        val weight = Tools.dealWeightOld(data.data,data.length)
        if(!TextUtils.isEmpty(weight)) {
            LogUtils.logGGQ("地磅表头重量：${weight}")
            tvResult?.text = "${"地磅表头重量：${weight}"}"
        } else {
            LogUtils.logGGQ("地磅表头重量获取失败")
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_bluetooth_classic

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        btnBluetooth = findViewById(R.id.btn_bluetooth)
        btnBluetooth?.setOnClickListener {
            checkBluetooth()
        }
        btnDisconnect = findViewById(R.id.btn_disconnect)
        btnDisconnect?.setOnClickListener {
            bluetoothClient?.disconnect()
        }
        rvList = findViewById(R.id.rv_list)
        rvList?.let {
            it.layoutManager = LinearLayoutManager(this)
            it.adapter = listAdapter
        }
        tvResult = findViewById(R.id.tv_result)
    }

    private val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    override fun initData(savedInstanceState: Bundle?) {
        lifecycleScope.launch {
            bluetoothClient = CoroutineClient(this@BluetoothClassicActivity, ClientType.CLASSIC, uuid)
        }
    }

    private fun checkBluetooth() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("设备不支持蓝牙")
            return
        }
        val bluetoothManager: BluetoothManager? = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?
        bluetoothAdapter = bluetoothManager?.adapter
        if(bluetoothAdapter == null) {
            showToast("设备不支持蓝牙")
            return
        }
        bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
        enabledBluetoothAndLocation()
    }


    private fun enabledBluetoothAndLocation() {
        // 开启蓝牙
        if(!(bluetoothAdapter!!.isEnabled)){
            //不建议强制打开蓝牙，官方建议通过Intent让用户选择打开蓝牙
//            bluetoothAdapter.enable()
            launcherBluetoothResult.launch(Unit)
            return
        }
        // 开启位置服务，
        // 支持获取ble蓝牙扫描结果
        if (!isLocationOpen(applicationContext)) {
            launcherLocationResult.launch(Unit)
            return
        }

        onScanBluetoothDevices()

    }



    private val launcherBluetoothResult = registerForActivityResult(object :
        ActivityResultContract<Unit, Boolean>() {
        override fun createIntent(context: Context, input: Unit): Intent {
            return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
            return resultCode == Activity.RESULT_OK
        }
    }) {
        if(it != null && it) {
            showToast("已开启蓝牙")
            enabledBluetoothAndLocation()
        }
    }


    private val launcherLocationResult = registerForActivityResult(object :
        ActivityResultContract<Unit, Boolean>() {
        override fun createIntent(context: Context, input: Unit): Intent {
            return Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
            return resultCode == Activity.RESULT_OK
        }
    }) {
        if(it != null && it) {
            showToast("已开启位置服务")
            enabledBluetoothAndLocation()
        }
    }

    private fun isLocationOpen(context: Context): Boolean {
        if(Build.VERSION.SDK_INT <  Build.VERSION_CODES.M) return true
        val locationManager: LocationManager? = context.getSystemService(LOCATION_SERVICE) as LocationManager?
        //gps定位
        val isGpsProvider: Boolean = locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER)?: false
        LogUtils.logGGQ("=isGpsProvider=>${isGpsProvider}")
        //网络定位
        val isNetWorkProvider: Boolean = locationManager?.isProviderEnabled(LocationManager.NETWORK_PROVIDER)?: false
        LogUtils.logGGQ("=isNetWorkProvider=>${isNetWorkProvider}")

        return isGpsProvider || isNetWorkProvider
    }


    private fun onScanBluetoothDevices() {
        if(bluetoothLeScanner == null) {
            showToast("未获取到蓝牙扫描对象")
            return
        }
        scan()
    }


    private var bluetoothClient: CoroutineClient? = null
    private fun scan() {
        LogUtils.logGGQ("开始扫描蓝牙===》")
        listAdapter.clear()
        lifecycleScope.launch {
            runOnUiThread {
                showLoading()
            }
            bluetoothClient?.startScan(3000,onEndScan ={
                LogUtils.logGGQ("搜索蓝牙结束")
                runOnUiThread {
                    dismissLoading()
                }
            })?.collect { device ->
                runOnUiThread {
                    if(!TextUtils.isEmpty(device.name) && !listAdapter.isNotExist(device)) {
                        LogUtils.logGGQ("设备：${device.name}")
                        listAdapter.addDevice(device)
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        bluetoothClient?.release()
    }
}